package com.yupi.yupicturebackend.api.imagesearch.sub;

import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*获取图片列表地址*/
@Slf4j
public class GetImageFirstUrlApi {
    /* 获取图片列表页面地址*/

    public static String getImageFirstUrl(String url)
    {
        try{
            //使用Jsoup获取HTML内容
            Document document= Jsoup.connect(url).timeout(5000).get();
            //获取所有<script>标签
            Elements scriptElements = document.getElementsByTag("script");
            //遍历找到firstUrl的脚本内容
            for (Element scriptElement : scriptElements) {
                String scriptContent = scriptElement.html();
                if(scriptContent.contains("\"firstUrl\"")){
                    //正则表达式提取firstUrl的值
                    Pattern pattern = Pattern.compile("\"firstUrl\"\\s*:\\s*\"(.*?)\"");
                    Matcher matcher = pattern.matcher(scriptContent);
                    if(matcher.find()){
                        String firstUrl = matcher.group(1);
                        //处理转义
                        firstUrl = firstUrl.replace("\\/", "/");
                        return firstUrl;
                    }
                }

            }
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未找到 url");
        } catch (IOException e) {
            log.error("搜索失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "搜索失败");        }
    }

    public static void main(String[] args) {
        // 请求目标 URL
        String url = "https://graph.baidu.com/s?card_key=&entrance=GENERAL&extUiData[isLogoShow]=1&f=all&isLogoShow=1&session_id=9249134773628778963&sign=12626e97cd54acd88139901749537145&tpl_from=pc";
        String imageFirstUrl = getImageFirstUrl(url);
        System.out.println("搜索成功，结果 URL：" + imageFirstUrl);
    }
}
